package com.chongqing.shiro.service.impl;


import com.chongqing.shiro.mapper.UserMapper;
import com.chongqing.shiro.mapper.UserRoleMapper;
import com.chongqing.shiro.model.entity.User;
import com.chongqing.shiro.model.entity.UserRole;
import com.chongqing.shiro.model.vo.ResponseVo;
import com.chongqing.shiro.model.vo.ResultUtil;
import com.chongqing.shiro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: UserService实现类
 * -------------------
 * @Author: YangXingfu
 * @Date: 2019/01/04 12:57
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public int register(User user) {
        return userMapper.insert(user);
    }

    @Override
    public User selectByUsername(String username) {
        User user = null;
        try {
            user = userMapper.selectByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public void updateLastLoginTime(User user) {

        try {
            userMapper.updateLastLoginTime(user);
        } catch (Exception e) {
            throw new RuntimeException("更新登录时间失败");
        }
    }

    @Override
    public List<User> selectUsers(User user) {
        return userMapper.selectUsers(user);
    }

    @Override
    public User selectByUserId(String userId) {
        return userMapper.selectByUserId(userId);
    }

    @Override
    public int updateByUserId(User userForm) {
        return userMapper.updateByUserId(userForm);
    }

    @Override
    public int updateStatusBatch(List<String> userIdList, Integer statusInvalid) {
        Map<String, Object> params = new HashMap<String, Object>(2);
        params.put("userIds", userIdList);
        params.put("status", statusInvalid);
        return userMapper.updateStatusBatch(params);
    }

    @Override
    public ResponseVo addAssignRole(String userId, List<String> roleIdsList) {
        try{
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRoleMapper.delete(userRole);
            for(String roleId :roleIdsList){
                userRole.setId(null);
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
            return ResultUtil.success("分配角色成功");
        }catch(Exception e){
            return ResultUtil.error("分配角色失败");
        }
    }

    @Override
    public int updateUserByPrimaryKey(User newUser) {
        return userMapper.updateByPrimaryKey(newUser);
    }
}